﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;

using ABCat.Shared.Properties;

using Xceed.Wpf.Toolkit.PropertyGrid;
using Xceed.Wpf.Toolkit.PropertyGrid.Editors;

namespace ABCat.Core.Plugins
{
	public class ComboBoxEditor : ITypeEditor
	{
		#region + Fields +

		private static readonly Dictionary<string, ObservableCollection<object>> Sources = new Dictionary<string, ObservableCollection<object>>();

		#endregion
		#region + Logic +

		public static void Register([NotNull] string propertyItemName, [NotNull] ObservableCollection<object> itemsSource)
		{
			Sources[propertyItemName] = itemsSource;
		}

		public FrameworkElement ResolveEditor(PropertyItem propertyItem)
		{
			ObservableCollection<object> itemsSource;
			if (Sources.TryGetValue(propertyItem.PropertyDescriptor.Name, out itemsSource))
			{
				var fcmb = new ComboBox();
				var binding = new Binding("Value");

				binding.Source = propertyItem;
				binding.ValidatesOnExceptions = true;
				binding.ValidatesOnDataErrors = true;
				binding.Mode = propertyItem.IsReadOnly ? BindingMode.OneWay : BindingMode.TwoWay;
				BindingOperations.SetBinding(fcmb, ComboBox.SelectedValueProperty, binding);
				fcmb.ItemsSource = itemsSource;
				return fcmb;
			}
			throw new Exception("Источник данных для редактора свойства '{0}' не зарегистрирован".F(propertyItem.PropertyDescriptor.Name));
		}

		#endregion
	}

	public class LocalizationValueConverter : IValueConverter
	{
		#region + Properties +

		public Type TargetType		{get; set;}

		#endregion
		#region + Logic +

		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return ((Enum)value).GetDescription();
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return value.ToStringOrEmpty().GetEnumValueFromDescription(TargetType);
		}

		#endregion
	}
}